package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Dto.OrderDto;
import com.itheima.bean.*;
import com.itheima.common.PageParm;
import com.itheima.common.OrderPageParam;
import com.itheima.common.PageParm;
import com.itheima.common.PageParm;
import com.itheima.dao.OrderDao;
import com.itheima.service.*;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Transactional
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;


    @Autowired
    private OrderDao orderDao;


    /**
     * 添加订单表及订单明细表
     *
     * @param orders
     * @return
     */
    @Override
    public int insert(Orders orders, HttpSession session) {
        //设置订单号
        orders.setNumber(UUID.randomUUID().toString().replace("-", ""));
        //设置订单状态
        orders.setStatus(1);
        //设置下单用户ID
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);
        //设置结账和下单时间
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //设置实收金额
        List<ShoppingCart> shoppingCarts = shoppingCartService.selectByUserId();
        BigDecimal count = new BigDecimal(0.00);
        System.out.println(count);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            int number =shoppingCart.getNumber();
            BigDecimal numberBig = new BigDecimal(number);
            BigDecimal amount = shoppingCart.getAmount();
            BigDecimal cou = amount.multiply(numberBig);
            System.out.println("*****************************************");
            System.out.println(count);
            count=count.add(cou);
            System.out.println(count);
            System.out.println(cou);
        }
        orders.setAmount(count);

        //设置用户名
        User user = (User) session.getAttribute("user");
        orders.setUserName(user.getName());

        //设置手机号
        orders.setPhone(user.getPhone());

        //设置地址
        AddressBook addressBook = addressBookService.selectAddressById(orders.getAddressBookId());
        orders.setAddress(addressBook.getDetail());

        //设置收货人
        orders.setConsignee(addressBook.getConsignee());

        //添加订单表
        int row1 = orderDao.insert(orders);

        //添加订单详细表

        //流添加信息
        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((item -> {
            OrderDetail orderDetail = new OrderDetail();
            //添加菜品或者套餐ID
            if (item.getDishId() != null) {
                orderDetail.setDishId(item.getDishId());
            } else orderDetail.setSetmealId(item.getSetmealId());

            //添加订单ID
            orderDetail.setOrderId(orders.getId());

            //添加菜品或套餐名称
            orderDetail.setName(item.getName());

            //添加图片
            orderDetail.setImage(item.getImage());

            //添加金额
            orderDetail.setAmount(item.getAmount());

            //添加口味
            orderDetail.setDishFlavor(item.getDishFlavor());

            //添加数量
            orderDetail.setNumber(item.getNumber());

            return orderDetail;
        })).collect(Collectors.toList());

        if (orderDetailList != null && orderDetailList.size() != 0) {
            int row2 = 0;
            for (OrderDetail orderDetail : orderDetailList) {
                row2 += orderDetailService.insert(orderDetail);

            }
            return row2 == orderDetailList.size() ? 1 : 0;
        }
        return row1;
    }


    /**
     * 得到订单详情
     * @param param
     * @return
     */
    @Override
    public IPage<OrderDto> findByPage(PageParm param) {


        IPage<Orders> ordersPage = new Page<>(param.getPage(), param.getPageSize());
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId,BaseContext.getCurrentId()).orderByDesc(Orders::getCheckoutTime);
        IPage<Orders> orderList = orderDao.selectPage(ordersPage, lqw);
        List<OrderDto> orderDtos = orderList.getRecords().stream().map(order -> {
            List<OrderDetail> details= orderDetailService.findByOrderId(order.getId());
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order, orderDto);
            orderDto.setOrderDetails(details);
            return orderDto;
        }).collect(Collectors.toList());

        IPage<OrderDto> orderDtoIPage = new Page<>();
        orderDtoIPage.setRecords(orderDtos);
        orderDtoIPage.setTotal(orderList.getTotal());
        return orderDtoIPage;}
    /**
     * 分页查询
     *
     * @param pageParm
     * @return
     */
    @Override
    public IPage<Orders> look(OrderPageParam pageParm) throws ParseException {
        IPage<Orders> ordersPage = new Page<>(pageParm.getPage(), pageParm.getPageSize());
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date begin = null;
        Date end = null;
        if (pageParm.getBeginTime() != null) {
            begin = simpleDateFormat.parse(pageParm.getBeginTime());
            end = simpleDateFormat.parse(pageParm.getEndTime());
        }
        lqw.like(pageParm.getNumber() != null, Orders::getNumber, pageParm.getNumber())
                .ge(pageParm.getBeginTime() != null, Orders::getOrderTime, begin)
                .le(pageParm.getEndTime() != null, Orders::getOrderTime, end);
        IPage<Orders> ordersIPage = orderDao.selectPage(ordersPage, lqw);
        return ordersIPage;
    }
    }
